"use client";

import React, { useState, useEffect } from "react";
import { Form, Input, Button, Checkbox, Row, Col, message } from "antd";
import { UserOutlined, LockOutlined } from "@ant-design/icons";
import { useRouter, useSearchParams } from "next/navigation";
import Image from "next/image";
import { getCodeApi, loginApi, getWarehouseAuthTokenApi } from "./api";
import { useAuthStore } from "@/app/cg06/store/useAuthStore";
import styles from "./index.module.scss";
import { useAuthStore2 } from "@/app/cg06/store/useAuthStore2";

interface LoginForm {
  username: string;
  password: string;
  code: string;
  uuid: string;
}

interface CodeResponse {
  captchaEnabled: boolean;
  img: string;
  uuid: string;
}

const LoginPage: React.FC = () => {
  const [form] = Form.useForm();
  const router = useRouter();
  const searchParams = useSearchParams();
  const redirect = searchParams.get("redirect");
  const setToken = useAuthStore((s) => s.setToken);
  const setToken2 = useAuthStore2((s) => s.setToken);
  const [loading, setLoading] = useState(false);
  const [codeUrl, setCodeUrl] = useState("");
  const [captchaEnabled, setCaptchaEnabled] = useState(true);
  const [loginForm, setLoginForm] = useState<LoginForm>({
    username: "",
    password: "",
    code: "",
    uuid: "",
  });

  // 获取验证码
  const getCode = async () => {
    try {
      // 这里需要替换为实际的API调用
      const res = await getCodeApi();

      setCaptchaEnabled(res.captchaEnabled !== false);
      if (res.captchaEnabled !== false) {
        setCodeUrl("data:image/gif;base64," + res.img);
        setLoginForm((prev) => ({ ...prev, uuid: res.uuid }));
      }
    } catch (error) {
      console.error("获取验证码失败:", error);
    }
  };

  // 处理登录
  const handleLogin = async () => {
    try {
      await form.validateFields();
      setLoading(true);

      const res = await loginApi(loginForm);
      setToken(res.access_token);
      
      const res2 = await getWarehouseAuthTokenApi();
      
      setToken2(res2);
      setLoading(false);
      const url = process.env.NEXT_PUBLIC_APP_ENV === 'development' ? '/cg06/navigation' : '/cg06/navigation.html'
      router.push(url);
    } catch (error) {
      setLoading(false);
      if (captchaEnabled) {
        getCode();
      }
    }
  };

  // 处理表单值变化
  const handleFormChange = (
    changedValues: Partial<LoginForm>,
    allValues: LoginForm
  ) => {
    // uuid不能变
    allValues.uuid = loginForm.uuid;
    setLoginForm(allValues);
  };

  // 处理回车键登录
  const handleKeyPress = (e: React.KeyboardEvent) => {
    if (e.key === "Enter") {
      handleLogin();
    }
  };

  useEffect(() => {
    getCode();
  }, []);

  return (
    <div className={styles.pageContainer}>
      <div className={styles.login}>
        <div className={styles.banner}>
          <div style={{ position: "absolute", top: 0, left: 0 }}>
            <Image
              src="https://uat-base.oss-cn-hangzhou.aliyuncs.com/newLogo.png"
              alt="logoImage"
              width={106}
              height={30}
            />
          </div>
        </div>
        <div className={styles.formRight}>
          <div className={styles.login2}>
            <div className={styles.lgTitle}>智捷元港-商城六期展厅</div>
            <div className={styles.subTitle}>请登录你的账号</div>

            <Form
              form={form}
              className={styles.loginForm}
              onValuesChange={handleFormChange}
              initialValues={loginForm}
              layout="vertical"
            >
              <Form.Item
                name="username"
                label="账号"
                rules={[{ required: true, message: "请输入您的账号" }]}
              >
                <Input
                  placeholder="请输入账号"
                  size="large"
                  prefix={<UserOutlined />}
                />
              </Form.Item>

              <Form.Item
                name="password"
                label="密码"
                rules={[{ required: true, message: "请输入您的密码" }]}
              >
                <Input.Password
                  size="large"
                  placeholder="请输入密码"
                  prefix={<LockOutlined />}
                />
              </Form.Item>

              {captchaEnabled && (
                <Form.Item
                  name="code"
                  label="验证码"
                  rules={[{ required: true, message: "请输入验证码" }]}
                >
                  <Row gutter={16}>
                    <Col flex="auto">
                      <Input size="large" placeholder="请输入验证码" />
                    </Col>
                    <Col>
                      <div className={styles.loginCode}>
                        <img
                          src={codeUrl}
                          className={styles.loginCodeImg}
                          onClick={getCode}
                          alt="验证码"
                        />
                      </div>
                    </Col>
                  </Row>
                </Form.Item>
              )}

              {/* <div style={{ margin: "-8px 0px 40px" }}>
                <Form.Item
                  name="rememberMe"
                  valuePropName="checked"
                  style={{ marginBottom: 0 }}
                >
                  <Checkbox className={styles.loginCheckbox}>记住密码</Checkbox>
                </Form.Item>
              </div> */}

              <Form.Item style={{ width: "100%" }}>
                <Button
                  className={styles.loginBtnSubmit}
                  type="primary"
                  size="large"
                  loading={loading}
                  onClick={handleLogin}
                  style={{ width: "100%" }}
                >
                  {loading ? "登 录 中..." : "登 录"}
                </Button>
              </Form.Item>
            </Form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;
